package com.hmdp.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.UserHolder;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        /*// 1.获取session
        HttpSession session = request.getSession();

        //2.从session中获取用户
        User user = (User) session.getAttribute(USER_SESSION_ID);*/

       /* // 请求头中获取token
        String token = request.getHeader(HEAD_AUTHORIZATION);
        if (StrUtil.isBlankIfStr(token)){
            response.setStatus(401);
            return false;
        }
        //2. 从redis获取数据
        String key = LOGIN_USER_KEY + token;
        Map<Object, Object> objectMap = stringRedisTemplate.opsForHash().entries(key);
        //3. 判断redis中是否存在
        if (objectMap.isEmpty()){
            response.setStatus(401);
            return false;
        }
        UserDTO dto = BeanUtil.fillBeanWithMap(objectMap, new UserDTO(), false);

        //4.存在,保存到ThreadLocal
        UserHolder.saveUser(dto);
        //6.刷新token有效期
        stringRedisTemplate.expire(key, Duration.ofMinutes(LOGIN_USER_TTL));
        //5.放行*/

        UserDTO user = UserHolder.getUser();
        if (user == null){
            response.setStatus(401);
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理ThreadLocal中的用户信息，防止内存泄漏和线程间数据污染
        UserHolder.removeUser();
    }
}
